//
//  HMComposeViewController.swift
//  VVeibo21
//
//  Created by Apple on 16/11/1.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

import SVProgressHUD

//  发微博视图控制器
class HMComposeViewController: UIViewController {

    // MARK: - 懒加载控件
    fileprivate lazy var titleLabel: UILabel = {
    
        let label = UILabel()
        
       
        label.textColor = UIColor.darkGray
        label.font = UIFont.systemFont(ofSize: 17)
        label.textAlignment = .center
        //  指定多行显示
        label.numberOfLines = 0
        //  判断是name 是否为 nil
        if let name = HMUserAccountViewModel.sharedTools.userAccountModel?.screen_name {
            let title = "发微博\n" + name
            //  创建富文本
            let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: title)
            //  获取 name 的 rang
            let range = (title as NSString).range(of: name)
            
            attributedString.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.brown], range: range)
            
            //  设置富文本
            label.attributedText = attributedString
            
            
            
            
        } else {
            label.text = "发微博"
        }
        
        
        
        label.sizeToFit()
        
        return label
        
    }()
    
    //  发送按钮
    fileprivate lazy var sendButton: UIButton = {
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        //  设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        //  设置文字及颜色
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        //  设置字体大小
        button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        //  设置大小
        button.size = CGSize(width: 45, height: 35)
        
        return button
    }()
    
    //  textView ,输入框
    fileprivate lazy var textView: HMComposeTextView = {
        let composeTextView = HMComposeTextView()
        composeTextView.placeHolder = "别低头,绿帽会掉~别低头,绿帽会掉~v别低头,绿帽会掉~别低头,绿帽会掉~v"
        composeTextView.font = UIFont.systemFont(ofSize: 14)
        //  设置隐藏纠错提示
//        composeTextView.autocorrectionType = .no
        //  设置代理
        composeTextView.delegate = self
        //  textview 能够拖动
        composeTextView.alwaysBounceVertical = true
        return composeTextView
    }()
    
    //  toolBar
    fileprivate lazy var toolBar: HMComposeToolBar = {
        let composeToolBar = HMComposeToolBar()
        return composeToolBar
    }()
    
    //  添加撰写配图
    fileprivate lazy var pictureView: HMComposePictureView = {
        let view = HMComposePictureView()
        view.backgroundColor = self.textView.backgroundColor
        return view
    }()
    
    //  表情键盘视图
    fileprivate lazy var emoticonKeyboard: HMEmoticonKeyBoard = {
        let keybard = HMEmoticonKeyBoard()
        //  设置自定义键盘的大小
        keybard.size = CGSize(width: self.textView.width, height: 216)
        
        return keybard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        setupUI()
    }
    //  添加控件设置约束
    private func setupUI() {
        //  键盘键盘 frame 的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardFrameChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        //  监听表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonButtonNotiAction(noti:)), name: NSNotification.Name(DidSelectedEmoticonButtonNotification), object: nil)
        //  监听删除表情按钮的点击
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteEmoitconAction), name: NSNotification.Name(DidSelectedDeleteEmotionButtonNotification), object: nil)
        
        setupNavUI()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        textView.snp_makeConstraints { (make) in
            make.top.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.height.equalTo(35)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.centerX.equalTo(textView)
            make.top.equalTo(textView).offset(100)
            make.width.equalTo(textView.snp_width).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
            
        }
        
        
        
        //  设置 toolbar 需要的闭包
        toolBar.callBack = { [weak self] (type: HMComposeToolBarButtonType) in
            switch type {
            case .picture:
                print("图片")
                self?.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
                print("表情")
                self?.didSelectedEmoticon()
            case .add:
                print("加号")
            }
        }
        //  设置配图的闭包
        pictureView.callBack = { [weak self] in
             self?.didSelectedPicture()
        }
        
    
    }

    //  设置导航栏视图操作
    private func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target:  self, action: #selector(cancelAction))
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //  默认不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    // MARK: - 点击导航栏按钮操作
    
    @objc private func sendAction() {
        
        //  获取 token
        let accessToken = HMUserAccountViewModel.sharedTools.accessToken!
        //  获取微博内容
//        let status = textView.text!
        let status = textView.emoticonText
        
        
        SVProgressHUD.show()
        
        if pictureView.images.count > 0 {
            //  表示有图片, 执行发送带图片的微博数据
            let image = pictureView.images.first!
            
            HMNetworkTools.sharedTools.upload(access_token: accessToken, status: status, image: image, success: { (response) in
                    SVProgressHUD.showSuccess(withStatus: "发送成功")
                }, failure: { (error) in
                    print(error)
                    SVProgressHUD.showError(withStatus: "发送失败")
            })
            
            
        } else {
            HMNetworkTools.sharedTools.update(access_token: accessToken, status: status, success: { (reponse) in
                
                SVProgressHUD.showSuccess(withStatus: "发送成功")
                
            }) { (error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发送失败")
            }
        }
        
        
        //  以下代码已经抽取到 HMComposeTextView+Extension 里面
        //        var result = ""
        //        //  遍历富文本
        //        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: []) { (info, range, _) in
        //            // (info, range, _)
        //            /*
        //                info: 富文本的描述信息
        //                range: 富文本的范围
        //                UnsafeMutablePointer :  遍历是否停止标记
        //             */
        //
        //            print(info)
        //
        //            if let attachment = info["NSAttachment"] as? HMTextAttachment {
        //                //  表示是图片表情富文本
        //                let emoticon = attachment.emoticon!
        //
        //
        //                result += emoticon.chs!
        //
        //            } else {
        //                //  文字富文本
        //
        //                //  根据文字富文本的范围获取对应的范围的富文本
        //                let textAttributedStr = textView.attributedText.attributedSubstring(from: range)
        //
        //                //  根据富文本获取对应的字符串
        //                let text = textAttributedStr.string
        //                result += text
        //                
        //                //print(NSStringFromRange(range))
        //                
        //            }
        //        }
        
        
        
    
    }
    
    
    @objc private func cancelAction() {
        
        //textView.resignFirstResponder()
        self.view.endEditing(true)
        
        dismiss(animated: true, completion: nil)
    
    }
    
    // MARK: - 监听删除表情按钮点击的方法
    @objc private func didSelectedDeleteEmoitconAction() {
        //  删除操作
        textView.deleteBackward()
    }
    
    // MARK: - 监听表情按钮的点击
    @objc private func didSelectedEmoticonButtonNotiAction(noti: Notification) {
        //  获取对应的通知参数
        let emoticon = noti.object as! HMEmoticon
 
        textView.insertEmoticon(emoticon: emoticon)
        
        
        //  保存点击的表情模型-> 那么allEmoticonArray 数据源发生了改变 需要重新加载数据
        HMEmoticonTools.shareTool.saveRecentEmoticon(emoticon: emoticon)
        
        //  刷新最近这组表情数据
        emoticonKeyboard.reloadRecentData()
        
        
//        if emoticon.type == "0" {
//            //  表示图片
//            //            textView.insertText(emoticon.chs!)
//            
//            //  记录上一次的富文本
//            let lastAttributedString = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            // 根据图片的全路径创建 UIImage 对象
//            let image = UIImage(named: emoticon.fullPath!)
//            // 根据 UIImage 对象创建文本附件(NSTextAttachment)
//            let attachment = NSTextAttachment()
//            //  给文本附件设置显示的图片
//            attachment.image = image
//            //  设置成为文字大小
//            let fontHeight = textView.font!.lineHeight
//            //  文本附件bounds大小
//            //  设置 bounds 会相应子控件的显示位置
//            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
//            // 根据文本附件创建富文本(NSAttributedString)
//            let attributedStr = NSAttributedString(attachment: attachment)
//            //  拼接富文本
//            //lastAttributedString.append(attributedStr)
//            
//            //  获取选中的富文本
//            var selectRange = textView.selectedRange
//            lastAttributedString.replaceCharacters(in: selectRange, with: attributedStr)
//            
//            //  设置富文本的字体大小
//            lastAttributedString.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, lastAttributedString.length))
//            
//            // 设置富文本
//            textView.attributedText = lastAttributedString
//            //  设置光标位置
//            selectRange.location += 1
//            //  设置范围的长度
//            selectRange.length = 0
//            textView.selectedRange = selectRange
//            
//        } else {
//            //  emoji
//            textView.insertText((emoticon.code! as NSString).emoji())
//        }
        
        
        
        
        
    }
    
    // MARK: - 监听键盘 frame 的改变
    @objc private func keyboardFrameChange(noti: Notification) {
        //  获取键盘的 frame
        let keybardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        
        //  动画时长
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //  更新 toolbar 底部约束
        toolBar.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keybardFrame.origin.y - HMSCREENH)
        }
        
        UIView.animate(withDuration: duration) { 
            self.view.layoutIfNeeded()
        }
       
        
    
    }
    
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
}


//  MARK: 点击 toolbar 的相关处理逻辑
extension HMComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    //  点击表情处理逻辑
    func didSelectedEmoticon() {
        
        if textView.inputView == nil {
            //  设置自定义输入视图
            textView.inputView = emoticonKeyboard
            // 代码执行到此,表示是表情键盘类型
            toolBar.showIcon(isEmoticon: true)
        } else {
            //  设置成为系统键盘
            textView.inputView = nil
            // 代码执行到此,表示是系统键盘类型
            toolBar.showIcon(isEmoticon: false)
        }
        
        //  设置自己定义在键盘上面的视图
//        textView.inputAccessoryView
        //  成为第一响应者
        textView.becomeFirstResponder()
        //  重新刷新自定义输入视图
        textView.reloadInputViews()
    
    }
    
    
    //  点击图片的处理逻辑
    func didSelectedPicture() {
        //  创建图片浏览器对象
        let imagePickerCtr = UIImagePickerController()
        //  设置代理对象
        imagePickerCtr.delegate = self
        //  判断是否支持相机
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            //  支持相机
            imagePickerCtr.sourceType = .camera
        } else {
            //  支持相册
            imagePickerCtr.sourceType = .photoLibrary
        }
        //  判断是否支持前置摄像头或者后置摄像头
        if UIImagePickerController.isCameraDeviceAvailable(.front) {
            //  表示支持前置摄像头
            print("支持前置摄像头")
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.rear) {
            //  表示支持后置摄像头
            print("支持后置摄像头")
        }
        
        if UIImagePickerController.isCameraDeviceAvailable(.front) == false && UIImagePickerController.isCameraDeviceAvailable(.rear) == false {
            print("摄像头不可用")
        }
        //  表示允许编辑 -> 如果开启了编辑,那么可以获取编辑或的这个图片UIImagePickerControllerEditImage
//        imagePickerCtr.allowsEditing = true
        
        
        self.present(imagePickerCtr, animated: true, completion: nil)
    
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
       
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //  获取压缩的后图片
        let currentScaleImage = scaleImage(scaleWidth: 200, image: image)
        //  添加显示的图片
        pictureView.addImage(image: currentScaleImage)
        //  如果实现了代理方法, 那么自己去 dismis 图片浏览器
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        print("你点击取消按钮")
        //  如果实现了代理方法, 那么自己去 dismis 图片浏览器
        picker.dismiss(animated: true, completion: nil)
    }
    
    //  根据指定压缩后的宽度,等比压缩图片
    private func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        
        //  宽度 100, 高度 200,  压缩后的宽度 50, 计算压缩后的高度
        //  计算压缩后的高度
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        //  压缩后的大小
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        //  开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        //  把图片渲染到指定的区域内
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        //  通过图片上下文获取当前的图片
        let currentScaleImage = UIGraphicsGetImageFromCurrentImageContext()
        
        //  关闭图片上下文
        UIGraphicsEndImageContext()
        return currentScaleImage!
    
    }
    
    
    

}



//  MARK: --UITextViewDelegate
extension HMComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        //  判断 textView 是否有内容,如果有内容那么按钮可用,否则不可用
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //  让键盘失去第一响应者
        self.view.endEditing(true)
    }
    

}












